﻿using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace FTBS.Models.DAO
{
    public class RoomDAO
    {
        private FilmTicketBookingSystemEntities _entities = new FilmTicketBookingSystemEntities();

        /// <summary>
        /// Get all room
        /// </summary>
        /// <returns>List of room</returns>
        /// <author>vuongvt</author>
        public IEnumerable<Room> GetListRoom()
        {
            try
            {
                IEnumerable<Room> listRoom = new List<Room>();
                listRoom = _entities.Rooms.ToList().Where(room => room.IsDeleted == false);
                return listRoom;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Get list room by theaterId. It is used when choose a theater -> load all room of this theater
        /// </summary>
        /// <param name="theaterId">TheaterId</param>
        /// <returns>SelectList of Room</returns>
        /// <author>vuongvt</author>
        public SelectList GetSelectedListRoomByTheater(int theaterId)
        {
            try
            {
                List<Room> listRoomHasChair = new List<Room>();
                IEnumerable<SelectListItem> listRoom = new List<SelectListItem>();

                var listRoomCheck = from room in _entities.Rooms
                                    where room.TheaterId == theaterId
                                          && room.IsDeleted == false
                                    select room;

                foreach (var item in listRoomCheck)
                {
                    if (IsRoomCreatedChair(item.RoomId))
                    {
                        listRoomHasChair.Add(item);
                    }
                }

                listRoom = listRoomHasChair.AsEnumerable().Select(room => new SelectListItem() { Value = room.RoomId.ToString(), Text = room.RoomName });

                return new SelectList(listRoom, "Value", "Text");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private bool IsRoomCreatedChair(int roomId)
        {
            try
            {
                var resultQuery = _entities.Chairs.Any(chair => chair.RoomId == roomId && chair.IsDeleted == false);
                return resultQuery;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Get list room by theaterId
        /// </summary>
        /// <param name="theaterId"></param>
        /// <returns>List of room</returns>
        /// <author>vuongvt</author>
        public List<Room> GetListRoomByTheater(int theaterId)
        {
            try
            {
                List<Room> listRoom = new List<Room>();
                listRoom = _entities.Rooms.Where(room => room.TheaterId == theaterId && room.IsDeleted == false).ToList();
                return listRoom;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Check room if it's ready exist
        /// </summary>
        /// <param name="room"></param>
        /// <returns></returns>
        /// <author>nguyenht</author>
        public bool CheckIsExisted(Room room)
        {
            var isExist = _entities.Rooms.Any(c => c.IsDeleted == false && c.RoomName == room.RoomName && c.TheaterId == room.TheaterId);
            return isExist;
        }
        public List<Int32> GetFrame(int theaterId)
        {
            List<Int32> list = new List<int>();
            var frameQuery = _entities.Theaters.Where(s => s.TheaterId == theaterId);
            foreach (var item in frameQuery)
            {
                list.Add(item.MaxColumnInRoom);
                list.Add(item.MaxChairInRow);
            }
            return list;
        }
        /// <summary>
        /// Create a room of a theater
        /// </summary>
        /// <param name="room"></param>
        /// <returns></returns>
        /// <author>nguyenht</author>
        public int Add(Room room)
        {
            try
            {
                room.IsDeleted = false;
                _entities.Rooms.Add(room);
                _entities.SaveChanges();
                return 1;
            }
            catch { return 0; }
        }

        public Room GetRoomById(int id)
        {
            try
            {
                var room = _entities.Rooms.Find(id);
                return (room);
            }
            catch { return null; }

        }
        public int Delete(Room room)
        {
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    var resultQuery = _entities.Chairs.Where(s => s.RoomId == room.RoomId);
                    foreach (var item in resultQuery)
                    {
                        item.IsDeleted = true;
                    }
                    room.IsDeleted = true;
                    _entities.SaveChanges();
                    trans.Complete();
                    return 1;
                }
                catch
                {
                    trans.Dispose();
                    return 0;
                }
            }
        }
        public int SaveChange(Room room)
        {
            try { _entities.SaveChanges(); return 1; }
            catch { return 0; }
        }



        /// <summary>
        /// Check the RoomId is used in Schedule and doesn't have Booked ticket or not
        /// This function is used for user Click to Edit in List Room
        /// </summary>
        /// <param name="showTimeId"></param>
        /// <returns>True: Is Exist ---- False: Not Exist</returns>
        /// <author>VuongVT</author>
        public bool IsRoomUsedInScheduleAndBooked(int roomId)
        {
            try
            {
                bool isUsedScheduleAndBooked = false;

                var scheduleId = (from schedule in _entities.Schedules
                                  where schedule.RoomId == roomId
                                        && schedule.IsDeleted == false
                                        && schedule.IsCreateTicket == true
                                  select schedule.ScheduleId).FirstOrDefault();

                if (scheduleId != 0)
                {
                    var isBookedTicket = _entities.Tickets.Any(ticket => ticket.ScheduleId == scheduleId
                                                                     && ticket.IsDeleted == false
                                                                     && ticket.Status == true);
                    if (isBookedTicket)
                    {
                        isUsedScheduleAndBooked = true;
                    }
                }
                return isUsedScheduleAndBooked;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Check the ShowTimeId is used in Schedule or not
        /// This function is used for user Click to Delete in List ShowTIme
        /// </summary>
        /// <param name="showTimeId"></param>
        /// <returns>True: Is Exist ---- False: Not Exist</returns>
        /// <author>VuongVT</author>
        public bool IsRoomUsedForSchedule(int roomId)
        {
            try
            {
                var isUsedForSchedule = _entities.Schedules.Any(schedule => schedule.RoomId == roomId
                                                                            && schedule.IsDeleted == false);
                return isUsedForSchedule;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}